//
//  GMHttpInvoker.m
//  NewCocosProject
//
//  Created by GM on 16/7/26.
//
//

#import "GMHttpInvoker.h"
#import "UCommUtil.h"


@interface GMHttpInvoker ()
{
    
}
@end

@implementation GMHttpInvoker

/**
 单例
 
 @return 当前类的单例
 */
+ (GMHttpInvoker *) shareManager {
    
    static GMHttpInvoker *manager = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        if (manager == nil) {
            manager = [[GMHttpInvoker alloc]init];
        }
    });
    return manager;
}

/**
 get 方式请求数据【异步请求】
 
 @param getUrl getUrl地址
 @param dic 数据
 @param successBlock 成功回调
 @param failureBlock 失败回调
 */
- (void)getWithUrl:(NSString *)getUrl withDictionary:(NSDictionary *)dic withSuccessBlock:(SuccessBlock)successBlock withFailureBlock:(FailureBlock)failureBlock
{
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSString* string =[NSString stringWithFormat:@"%@?%@",getUrl,[UCommUtil DictionaryTOUrlString:dic]];
    NSString* urlString = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //JSON数据反序列化
        //        多线程 可进行解析 耗时操作
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if (!error) {
                NSError *err = [[NSError alloc] init];
                
//                NSString * str  =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//                str=[str stringByReplacingOccurrencesOfString:@"\\" withString:@""];
//                NSData *JSONData = [str dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
                if (err.code != 0) {
                    NSLog(@"服务器返回数据解析错误：%@",err);
                }
                successBlock(response,dataDic);
            }else {
                NSLog(@"error : %@" , error);
                NSLog(@"domin : %@",error.userInfo);
                failureBlock(error);
            }
        }];
    }];
    //NSURLSession中的任务默认都是挂起的，执行这条语句之后任务才会执行
    [dataTask resume];
    
}


/**
 post 方式请求数据【异步请求】
 
 @param postUrl postUrl地址
 @param dic 数据
 @param successBlock 成功回调
 @param failureBlock 失败回调
 */
- (void)postAsync:(NSString *)postUrl withDictionary:(NSDictionary *)dic withSuccessBlock:(SuccessBlock)successBlock withFailureBlock:(FailureBlock)failureBlock
{
    NSLog(@"url : %@",postUrl);
    NSURL *url = [NSURL URLWithString:postUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    //如果往body内放东西
    if (dic) {
        NSString *dataString = [UCommUtil DictionaryTOUrlString:dic];
        NSData *bodyData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
        request.HTTPBody = bodyData;
    }else {
        NSLog(@"参数有误");
    }
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            //        多线程 可进行解析 耗时操作
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (!error) {
                    NSError *err = [[NSError alloc] init];
                    NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
                    if (err.code != 0) {
                        NSLog(@"服务器返回数据解析错误：%@",err);
                    }
                    successBlock(response,dataDic);
                }else {
                    NSLog(@"error : %@" , error);
                    NSLog(@"domin : %@",error.userInfo);
                    failureBlock(error);
                }
            }];
        }];
        [dataTask resume];
}

@end
